#!/bin/bash
set -e

cd /home/linaro/Desktop/cabinet_board

echo "==== git pull with credentials ===="
git pull https://bdy-fan-wenyu:Fwy20030721@gitee.com/bdy-fan-wenyu/cabinet_board.git || exit 1

echo "==== build ===="
cd build
cmake ..
make -j20

echo "==== kill old cabinet_board_main ===="
pids=$(pgrep -f "./cabinet_board_main")
if [ -n "$pids" ]; then
  echo "Killing cabinet_board_main: $pids"
  kill $pids
  # 用后台方式延迟启动新进程，避免脚本被kill
  nohup bash -c 'sleep 10; cd /home/linaro/Desktop/cabinet_board/build; ./cabinet_board_main > cabinet_board_main.log 2>&1 &' &
  echo "已发送重启命令，稍后自动启动新主程序"
  exit 0
fi

echo "==== check executable ===="
if [ ! -f ./cabinet_board_main ]; then
  echo "cabinet_board_main not found, build failed!"
  exit 1
fi

echo "==== run new cabinet_board_main ===="
nohup ./cabinet_board_main > cabinet_board_main.log 2>&1 &

sleep 2
echo "==== process check ===="
ps aux | grep cabinet_board_main | grep -v grep

echo "==== done ===="